package com.example.reward.fragments;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.reward.R;
import com.example.reward.adapter.HistoryAdapter;
import com.example.reward.api.ApiCallback;
import com.example.reward.api.ApiClient;
import com.example.reward.api.RewardApi;
import com.example.reward.response.RewardResultDto;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class HistoryFragment extends Fragment {

    private final RewardApi rewardApi = ApiClient.getClient().create(RewardApi.class);
    private static List<RewardResultDto> memoryCache = null; // 内存缓存
    private RecyclerView recyclerView;

    public HistoryFragment() {
        super(R.layout.fragment_history);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView = view.findViewById(R.id.historyRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 1. 优先显示内存缓存
        if (memoryCache != null && !memoryCache.isEmpty()) {
            recyclerView.setAdapter(new HistoryAdapter(requireContext(), memoryCache));
        } else {
            // 2. 尝试加载本地缓存
            List<RewardResultDto> localCache = loadCache();
            if (localCache != null && !localCache.isEmpty()) {
                recyclerView.setAdapter(new HistoryAdapter(requireContext(), localCache));
                memoryCache = localCache; // 同步到内存缓存
            }
        }

        // 3. 再异步刷新数据
        rewardApi.getResult().enqueue(new ApiCallback<>() {
            @Override
            public void onSuccess(List<RewardResultDto> result) {
                memoryCache = result; // 更新内存缓存
                saveCache(result);    // 保存到本地
                recyclerView.setAdapter(new HistoryAdapter(requireContext(), result));
            }

            @Override
            public void onError(String errorMsg) {
                Snackbar.make(view, "加载历史数据失败：" + errorMsg, Snackbar.LENGTH_LONG).show();
            }
        });
    }

    // 保存到本地缓存
    private void saveCache(List<RewardResultDto> list) {
        SharedPreferences prefs = requireContext().getSharedPreferences("history_cache", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("data", new Gson().toJson(list)); // 需要 Gson
        editor.apply();
    }

    // 从本地缓存读取
    private List<RewardResultDto> loadCache() {
        SharedPreferences prefs = requireContext().getSharedPreferences("history_cache", Context.MODE_PRIVATE);
        String json = prefs.getString("data", null);
        if (json != null) {
            Type listType = new TypeToken<List<RewardResultDto>>() {
            }.getType();
            return new Gson().fromJson(json, listType);
        }
        return new ArrayList<>();
    }
}
